package pl.poznan.put.cs.to.tsp.hea;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import pl.poznan.put.cs.to.tsp.common.IResultHolder;

public class PopulationManager {
	private List<IResultHolder> population;
	private int populationSize;
	private Random random;

	public PopulationManager(int size) {
		this.populationSize = size;
		this.population = new ArrayList<IResultHolder>();
		this.random = new Random();
	}

	public void killPercentOfPopulation(double percent) {
		int numToKill = (int) (this.populationSize * percent);
		this.population = this.population.subList(0, this.populationSize
				- numToKill);
	}

	public boolean addToPopulation(IResultHolder newResult) {
		boolean change = false;
		if (this.population.size() < this.populationSize) {
			this.population.add(newResult);
			change = true;
		} else {
			if (!this.population.contains(newResult)) {
				if (this.population.get(this.populationSize - 1).compareTo(
						newResult) > 0) {
					this.population.remove(this.populationSize - 1);
					this.population.add(newResult);
					change = true;
				}
			}
		}
		Collections.sort(this.population);
		return change;
	}

	public IResultHolder getBest() {
		return this.population.get(0);
	}

	public List<IResultHolder> getPopulation() {
		return this.population;
	}

	public IResultHolder drawResult(IResultHolder without) {
		int index;
		if (without == null) {
			index = this.random.nextInt(this.populationSize);
			return this.population.get(index);
		} else {
			index = this.random.nextInt(this.populationSize - 1);
			if (index >= this.population.indexOf(without)) {
				index++;
			}
			return this.population.get(index);
		}
	}
}
